package icu.zqyhdm.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.zqyhdm.blog.mapper.UserMapper;
import icu.zqyhdm.blog.vo.UserInfoVo;
import icu.zqyhdm.exception.MyException;
import icu.zqyhdm.helper.JwtHelper;
import icu.zqyhdm.result.ResultCodeEnum;
import icu.zqyhdm.blog.entity.Friend;
import icu.zqyhdm.blog.entity.User;
import icu.zqyhdm.blog.mapper.FriendMapper;
import icu.zqyhdm.blog.service.FriendService;
import icu.zqyhdm.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author lifu
 * @Date 2021/6/23 9:40
 */
@Service
public class FriendServiceImpl extends ServiceImpl<FriendMapper, Friend> implements FriendService {
    @Autowired
    private UserMapper userMapper;

    //查询全部好友
    @Override
    @Cacheable(value = "blog:friendList",key ="#userId")
    public List<UserInfoVo> selectList(Integer userId) {
        List<Friend> friendList = baseMapper.selectList(new QueryWrapper<Friend>().eq("user_id",userId));
        List<Integer> friendIdList = friendList.stream()
                .map(Friend::getFriendId).collect(Collectors.toList());
        List<User> userList = userMapper.selectList(new QueryWrapper<User>()
                .in("id", friendIdList));
        List<UserInfoVo> userInfoVos = BeanUtil.copyToList(userList, UserInfoVo.class);
        return userInfoVos;
    }

    //添加好友
    @Override
    @CacheEvict(value = "blog:friendList", key ="#userId")
    public void saveFriend(Integer userId, Integer friendId) {
        Friend friend = new Friend();
        friend.setUserId(userId);
        friend.setFriendId(friendId);
        int i = baseMapper.insert(friend);
        if(i < 1){
            throw new MyException(ResultCodeEnum.NET_ERROR);
        }
    }
}
